#include "linked_stack.h"
#include <stdlib.h>
#include <string.h>

/*
typedef struct node {
  void *data;
  node *next;
} node;
typedef struct linked_stack_t {
  node *top;
  size_t size;
  size_t nmemb;
} Stack;
*/

int stack_init(Stack **st, size_t size) {
  *st = malloc(sizeof(Stack));
  if (*st == NULL) {
    return -1;
  }
  (*st)->top = NULL;
  (*st)->nmemb = 0;
  (*st)->size = size;
  return 1;
}

int stack_empty(const Stack *st) { return st->nmemb == 0; }

size_t stack_nmemb(const Stack *st) { return st->nmemb; }

void stack_pop(Stack *st) {
  node *del_node = st->top;
  st->top = st->top->next;
  free(del_node->data);
  del_node->data = NULL;
  del_node->next = NULL;
  free(del_node);
  del_node = NULL;
  st->nmemb--;
}

void *stack_top(const Stack *st) { return st->top->data; }

int stack_push(Stack *st, const void *data) {
  node *new_node = malloc(sizeof(node));
  if (new_node == NULL) {
    return -1;
  }
  new_node->data = malloc(st->size);
  if (new_node->data == NULL) {
    free(new_node);
    new_node = NULL;
    return -1;
  }
  memcpy(new_node->data, data, st->size);
  new_node->next = st->top;
  st->top = new_node;
  st->nmemb++;
  return 1;
}

void stack_destory(Stack **st) {
  while (stack_empty(*st) == 0) {
    node *del_node = (*st)->top;
    (*st)->top = (*st)->top->next;
    free(del_node->data);
    del_node->data = NULL;
    del_node->next = NULL;
    free(del_node);
    del_node = NULL;
    (*st)->nmemb--;
  }
}
